﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Collections.Generic;
using EasyMvc.DbContext;
using EasyMvc.Config;
using EasyMvc.Models;
using EasyMvc.Utility;
using EasyMvc.Core;

namespace EasyMvc.Web.Common
{
    public class MWebControllerBase : EasyMvc.Core.ControllerBase
    {
        public MyDbContext DbContext {get; private set; }

        public MWebControllerBase()
        {
            this.DbContext = new MyDbContext();
        }

        public MWebConfigContext ConfigContext
        {
            get
            {
                return Sington<MWebConfigContext>.Instance;
            }
        }

        public MWebHttpContext MHttpContext
        {
            get
            {
                return Sington<MWebHttpContext>.Instance;
            }
        }
        
        public UserContext UserContext
        {
            get
            {
                return new UserContext(this.MHttpContext.UserName, this.DbContext);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
                this.DbContext.Dispose();
            
            base.Dispose(disposing);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            var noAuthorizeAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeIgnoreAttribute), false);
            if (noAuthorizeAttributes.Length > 0)
                return;

            if (this.UserContext.User == null)
            {
                var loginUrl = Url.Action("Login", "User");
                filterContext.Result = Redirect(loginUrl);
                return;
            }

            if (!PermissionHelper.HasPermission(filterContext, this.UserContext))
            {
                if (Request.UrlReferrer != null)
                    filterContext.Result = this.Stop("没有权限！", Request.UrlReferrer.AbsoluteUri);
                else
                    filterContext.Result = Content("没有权限！");
            }
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            if (filterContext.ActionDescriptor.ActionName.Equals("Index"))
                this.ModelState.Clear();
        }

        protected override void RenderViewData()
        {
            base.RenderViewData();

            var adminMenu = this.ConfigContext.Get<AdminMenu>();
            this.ViewData.Add("AdminMenu", adminMenu);

            this.ViewData.Add("UserContext", UserContext);
        }

        protected override void LogException(Exception exception)
        {
            base.LogException(exception);
            Logger.Instance.Exception(exception);
        }
    }
}
